package com.kzd.gtgame.provider

import android.content.ContentProvider
import android.content.ContentUris
import android.content.ContentValues
import android.content.UriMatcher
import android.database.Cursor
import android.net.Uri
import android.util.Log
import androidx.room.Room
import com.blankj.utilcode.util.LogUtils
import com.kzd.gtgame.app.GTApplication
import com.kzd.gtgame.db.AppDatabase
import com.kzd.gtgame.db.GameMember
import com.kzd.gtgame.db.GameMemberDao

class AppContentProvider : ContentProvider() {

    private val sUriMatcher = UriMatcher(UriMatcher.NO_MATCH).apply {
        addURI("com.kzd.gtgame.provider", "GameMember", 1)
    }

    private lateinit var mMemberDao: GameMemberDao

    override fun onCreate(): Boolean {
        val context = this.context
            ?: return false
        val appDatabase = Room.databaseBuilder(
            context, AppDatabase::class.java, GTApplication.DB_NAME
        )
            .fallbackToDestructiveMigration()
            .allowMainThreadQueries()
            .build()
        mMemberDao = appDatabase.gameMemberDao()
        return true
    }

    override fun query(
        uri: Uri,
        projection: Array<out String>?,
        selection: String?,
        selectionArgs: Array<out String>?,
        sortOrder: String?
    ): Cursor? {
        Log.e("TAG","==========query")
        if (sUriMatcher.match(uri) != 1) {
            return null
        }
        return mMemberDao.loadAll()
    }

    override fun getType(uri: Uri): String? {
        if (sUriMatcher.match(uri) != 1) {
            return null
        }
        return "GameMember"
    }

    override fun insert(uri: Uri, values: ContentValues?): Uri? {
        if (sUriMatcher.match(uri) != 1) {
            return null
        }
        val index = mMemberDao.insert(GameMember().apply {
            member = values?.get("member")?.toString() ?: return null
        })
        if (index > 0) {
            return ContentUris.withAppendedId(uri, index)
        }
        return null
    }

    override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int {
        if (sUriMatcher.match(uri) != 1) {
            return 0
        }
        mMemberDao.delete()
        return 1
    }

    override fun update(
        uri: Uri,
        values: ContentValues?,
        selection: String?,
        selectionArgs: Array<out String>?
    ): Int {
        if (sUriMatcher.match(uri) != 1) {
            return 0
        }
        mMemberDao.update(GameMember().apply {
            member = values?.get("member")?.toString() ?: return 0
        })
        return 1
    }
}